import { Component, OnInit } from '@angular/core';
import { TableService } from './service/table.service';

@Component({
  selector: 'common-table',
  templateUrl: './table.component.html',
  styleUrls: ['./table.component.scss']
})

export class TableComponent implements OnInit {

  //初始化
  tableConfig: any = {
    loading: false,
    total: 10,
    pageIndex: 1,
    pageSize: 10,
    filterGender: [
      { text: 'male', value: 'male' },
      { text: 'female', value: 'female' }
    ],
    tableBody: []
  };

  constructor(private serviceApi: TableService) { }

  ngOnInit() {}

  onQueryParamsChange(params: any) {

    const { pageSize, pageIndex, sort, filter } = params;
    const currentSort = sort.find((item: any) => item.value !== null);
    const sortField = (currentSort && currentSort.key) || null;
    const sortOrder = (currentSort && currentSort.value) || null;

    this.listApiService(pageIndex, pageSize, sortField, sortOrder, filter);
  }

  listApiService(
    pageIndex: number,
    pageSize: number,
    sortField: string | null,
    sortOrder: string | null,
    filters: Array<{ key: string; value: string[] }>
  ) {
    //过滤
    let _ft = "";
    if (filters.length != 0) {
      filters.forEach(filter => {
        filter.value.forEach(value => {
          _ft += "&" + filter.key + "=" + value;
        });
      });
    }

    let queryStr = `page=${pageIndex}&results=${pageSize}&sortField=${sortField}&sortOrder=${sortOrder}${_ft}`;

    this.tableConfig.loading = true;

    this.serviceApi.listApi(queryStr).subscribe((data: any) => {

      this.tableConfig.loading = false;
      this.tableConfig.total = 200;
      let res = data.results;

      if (res.length != 0) {
        this.tableConfig.tableBody = res;
      }

    });

  }
}
